<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`管理角色权限 - ${roleInfo?.roleName}`"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading" class="permission-management">
      <!-- 角色信息 -->
      <div class="role-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色标识">
            <el-tag type="info">{{ roleInfo?.roleKey }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="角色名称">
            {{ roleInfo?.roleName }}
          </el-descriptions-item>
          <el-descriptions-item label="角色状态">
            <el-tag :type="getRoleStatusType(roleInfo?.status) as any">
              {{ formatRoleStatus(roleInfo?.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户数量">
            {{ roleInfo?.userCount || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="角色描述" :span="2">
            {{ roleInfo?.description || "暂无描述" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 权限操作区 -->
      <div class="permission-actions">
        <div class="action-header">
          <h4>权限分配</h4>
          <div class="action-buttons">
            <el-button
              type="primary"
              size="small"
              :loading="saving"
              :disabled="!hasChanges"
              @click="handleSavePermissions"
            >
              保存权限
            </el-button>
            <el-button
              type="warning"
              size="small"
              :disabled="!currentPermissions.length"
              @click="handleRemoveAllPermissions"
            >
              移除所有权限
            </el-button>
            <el-button
              size="small"
              :disabled="!hasChanges"
              @click="handleResetPermissions"
            >
              重置
            </el-button>
          </div>
        </div>

        <!-- 权限选择区 -->
        <div class="permission-selection">
          <div class="selection-header">
            <el-checkbox
              v-model="selectAll"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            >
              全选权限 ({{ selectedPermissions.length }}/{{
                allPermissions.length
              }})
            </el-checkbox>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索权限..."
              size="small"
              style="width: 200px"
              clearable
            >
              <template #prefix>
                <IconifyIconOffline icon="ep:search" />
              </template>
            </el-input>
          </div>

          <!-- 权限列表 -->
          <div class="permission-list">
            <el-checkbox-group v-model="selectedPermissions">
              <div class="permission-grid">
                <div
                  v-for="permission in filteredPermissions"
                  :key="permission.id"
                  class="permission-item"
                  :class="{
                    'is-original': isOriginalPermission(permission.id),
                    'is-new': isNewPermission(permission.id)
                  }"
                >
                  <el-checkbox
                    :value="permission.id"
                    class="permission-checkbox"
                  >
                    <div class="permission-card">
                      <!-- 状态标签 -->
                      <div class="permission-status">
                        <el-tag
                          v-if="isOriginalPermission(permission.id)"
                          type="success"
                          size="small"
                          effect="light"
                        >
                          已有
                        </el-tag>
                        <el-tag
                          v-else-if="isNewPermission(permission.id)"
                          type="warning"
                          size="small"
                          effect="light"
                        >
                          新增
                        </el-tag>
                      </div>

                      <!-- 权限名称 -->
                      <div class="permission-title">
                        {{ permission.permName }}
                      </div>

                      <!-- 权限标识 -->
                      <div class="permission-key">
                        <el-tag size="small" type="info" effect="plain">
                          {{ permission.permKey }}
                        </el-tag>
                      </div>

                      <!-- 权限描述 -->
                      <div
                        v-if="permission.description"
                        class="permission-description"
                      >
                        {{ permission.description }}
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </div>
            </el-checkbox-group>
          </div>

          <!-- 空状态 -->
          <el-empty
            v-if="!filteredPermissions.length"
            description="没有找到匹配的权限"
            :image-size="100"
          />
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          type="primary"
          :loading="saving"
          :disabled="!hasChanges"
          @click="handleSavePermissions"
        >
          保存权限
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import {
  getRolePermissionsApi,
  getAllPermissionsApi,
  assignPermissionsToRoleApi,
  removeAllRolePermissionsApi,
  RoleManagementUtils,
  type RoleInfo,
  type PermissionInfo
} from "@/api/role-management";

interface Props {
  visible: boolean;
  roleInfo?: RoleInfo | null;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const dialogVisible = ref(false);
const loading = ref(false);
const saving = ref(false);
const searchKeyword = ref("");
const allPermissions = ref<PermissionInfo[]>([]);
const currentPermissions = ref<PermissionInfo[]>([]);
const originalPermissionIds = ref<number[]>([]);
const selectedPermissions = ref<number[]>([]);
const selectAll = ref(false);

// 工具函数
const formatRoleStatus = RoleManagementUtils.formatRoleStatus;
const getRoleStatusType = RoleManagementUtils.getRoleStatusType;

// 计算属性
const isIndeterminate = computed(() => {
  const selectedCount = selectedPermissions.value.length;
  const totalCount = filteredPermissions.value.length;
  return selectedCount > 0 && selectedCount < totalCount;
});

const filteredPermissions = computed(() => {
  if (!searchKeyword.value) {
    return allPermissions.value;
  }
  const keyword = searchKeyword.value.toLowerCase();
  return allPermissions.value.filter(
    permission =>
      permission.permName.toLowerCase().includes(keyword) ||
      permission.permKey.toLowerCase().includes(keyword) ||
      (permission.description &&
        permission.description.toLowerCase().includes(keyword))
  );
});

const hasChanges = computed(() => {
  return !RoleManagementUtils.compareRoleArrays(
    selectedPermissions.value,
    originalPermissionIds.value
  );
});

// 判断是否为原有权限
const isOriginalPermission = (permissionId: number) => {
  return originalPermissionIds.value.includes(permissionId);
};

// 判断是否为新增权限
const isNewPermission = (permissionId: number) => {
  return (
    selectedPermissions.value.includes(permissionId) &&
    !originalPermissionIds.value.includes(permissionId)
  );
};

// 监听visible变化
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val && props.roleInfo) {
      loadData();
    }
  },
  { immediate: true }
);

// 监听权限选择变化
watch(
  () => selectedPermissions.value,
  newVal => {
    const selectedCount = newVal.length;
    const totalCount = filteredPermissions.value.length;
    selectAll.value = selectedCount === totalCount && totalCount > 0;
  },
  { deep: true }
);

/**
 * 加载数据
 */
const loadData = async () => {
  await Promise.all([loadAllPermissions(), loadRolePermissions()]);
};

/**
 * 加载所有权限
 */
const loadAllPermissions = async () => {
  try {
    const response = await getAllPermissionsApi();
    if (response.code === 200 && response.data) {
      allPermissions.value = response.data;
    } else {
      ElMessage.error(response.message || "获取权限列表失败");
    }
  } catch (error) {
    console.error("加载权限列表失败:", error);
    ElMessage.error("获取权限列表失败");
  }
};

/**
 * 加载角色权限
 */
const loadRolePermissions = async () => {
  if (!props.roleInfo?.id) return;

  try {
    loading.value = true;
    const response = await getRolePermissionsApi(props.roleInfo.id);
    if (response.code === 200 && response.data) {
      currentPermissions.value = response.data;
      const permissionIds = RoleManagementUtils.extractPermissionIds(
        response.data
      );
      originalPermissionIds.value = [...permissionIds];
      selectedPermissions.value = [...permissionIds];
    } else {
      ElMessage.error(response.message || "获取角色权限失败");
    }
  } catch (error) {
    console.error("加载角色权限失败:", error);
    ElMessage.error("获取角色权限失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 全选/取消全选
 */
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedPermissions.value = RoleManagementUtils.extractPermissionIds(
      filteredPermissions.value
    );
  } else {
    // 只清除当前筛选结果中的权限，保留其他权限
    const filteredIds = RoleManagementUtils.extractPermissionIds(
      filteredPermissions.value
    );
    selectedPermissions.value = selectedPermissions.value.filter(
      id => !filteredIds.includes(id)
    );
  }
};

/**
 * 保存权限
 */
const handleSavePermissions = async () => {
  if (!props.roleInfo?.id) return;

  try {
    saving.value = true;
    const response = await assignPermissionsToRoleApi(
      props.roleInfo.id,
      selectedPermissions.value
    );
    if (response.code === 200) {
      ElMessage.success("权限分配成功");
      originalPermissionIds.value = [...selectedPermissions.value];
      emit("success");
    } else {
      ElMessage.error(response.message || "权限分配失败");
    }
  } catch (error) {
    console.error("保存权限失败:", error);
    ElMessage.error("权限分配失败");
  } finally {
    saving.value = false;
  }
};

/**
 * 移除所有权限
 */
const handleRemoveAllPermissions = async () => {
  if (!props.roleInfo?.id) return;

  try {
    await ElMessageBox.confirm(
      `确定要移除角色"${props.roleInfo.roleName}"的所有权限吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    saving.value = true;
    const response = await removeAllRolePermissionsApi(props.roleInfo.id);
    if (response.code === 200) {
      ElMessage.success("权限移除成功");
      selectedPermissions.value = [];
      originalPermissionIds.value = [];
      emit("success");
    } else {
      ElMessage.error(response.message || "权限移除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("移除权限失败:", error);
      ElMessage.error("权限移除失败");
    }
  } finally {
    saving.value = false;
  }
};

/**
 * 重置权限
 */
const handleResetPermissions = () => {
  selectedPermissions.value = [...originalPermissionIds.value];
  ElMessage.info("已重置为原始权限");
};

/**
 * 关闭对话框
 */
const handleClose = () => {
  emit("update:visible", false);
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto !important;
  }

  .permission-management {
    .permission-actions {
      .action-header {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;

        .action-buttons {
          justify-content: center;
        }
      }

      .permission-selection {
        .selection-header {
          flex-direction: column;
          gap: 12px;

          .el-input {
            width: 100% !important;
          }
        }

        .permission-list {
          max-height: 400px;

          .permission-grid {
            grid-template-columns: 1fr;
            gap: 16px;
            padding: 8px;
          }

          .permission-item {
            .permission-card {
              min-height: 120px;
              padding: 16px;

              .permission-title {
                padding-right: 50px;
                font-size: 15px;
              }

              .permission-status {
                top: 8px;
                right: 8px;
              }
            }
          }
        }
      }
    }
  }
}

.permission-management {
  .role-info {
    margin-bottom: 20px;

    :deep(.el-descriptions) {
      .el-descriptions__label {
        font-weight: 600;
      }
    }
  }

  .permission-actions {
    .action-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 12px;
      margin-bottom: 16px;
      border-bottom: 1px solid #e4e7ed;

      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .action-buttons {
        display: flex;
        gap: 8px;
      }
    }

    .permission-selection {
      .selection-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        margin-bottom: 16px;
        background-color: #f5f7fa;
        border-radius: 4px;
      }

      .permission-list {
        max-height: 500px;
        padding: 16px;
        overflow-y: auto;
        background-color: #fff;
        border: 1px solid #e4e7ed;
        border-radius: 8px;

        .permission-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
          gap: 20px;
          padding: 12px;
        }

        .permission-item {
          position: relative;
          overflow: hidden;
          background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
          border: 2px solid #e2e8f0;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgb(0 0 0 / 6%);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

          &:hover {
            border-color: #409eff;
            box-shadow: 0 8px 25px rgb(64 158 255 / 15%);
            transform: translateY(-4px);
          }

          &.is-original {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-color: #67c23a;

            &:hover {
              border-color: #529b2e;
              box-shadow: 0 8px 25px rgb(103 194 58 / 20%);
            }
          }

          &.is-new {
            background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
            border-color: #e6a23c;

            &:hover {
              border-color: #d69e2e;
              box-shadow: 0 8px 25px rgb(230 162 60 / 20%);
            }
          }

          .permission-card {
            position: relative;
            display: flex;
            flex-direction: column;
            height: 100%;
            min-height: 140px;
            padding: 20px;
            padding-top: 60px;

            .permission-status {
              position: absolute;
              top: 12px;
              right: 12px;
              z-index: 10;
            }

            .permission-title {
              position: absolute;
              top: 20px;
              left: 50%;
              z-index: 1;
              width: calc(100% - 40px);
              margin-bottom: 12px;
              font-size: 16px;
              font-weight: 600;
              line-height: 1.4;
              color: #1a202c;
              text-align: center;
              word-break: break-word;
              transform: translateX(-50%);
            }

            .permission-key {
              display: flex;
              justify-content: center;
              margin-top: 0;
              margin-bottom: 16px;

              .el-tag {
                padding: 4px 8px;
                font-family: Monaco, Menlo, "Ubuntu Mono", monospace;
                font-size: 11px;
                font-weight: 500;
                border-radius: 6px;
              }
            }

            .permission-description {
              flex: 1;
              padding: 12px 16px;
              margin-top: auto;
              font-size: 13px;
              line-height: 1.6;
              color: #64748b;
              text-align: center;
              word-break: break-word;
              background: rgb(248 250 252 / 80%);
              border: 1px solid rgb(226 232 240 / 60%);
              border-radius: 8px;
              backdrop-filter: blur(10px);
            }
          }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 自定义滚动条样式
.permission-list::-webkit-scrollbar {
  width: 6px;
}

.permission-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.permission-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  &:hover {
    background: #a8a8a8;
  }
}

// 复选框组样式优化
:deep(.el-checkbox-group) {
  width: 100%;

  .permission-checkbox {
    display: block;
    width: 100%;
    height: 100%;
    margin: 0;

    .el-checkbox__input {
      position: absolute;
      top: 16px;
      left: 16px;
      z-index: 20;

      .el-checkbox__inner {
        width: 18px;
        height: 18px;
        background-color: #fff;
        border: 2px solid #d1d5db;
        border-radius: 6px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:hover {
          border-color: #409eff;
          transform: scale(1.1);
        }
      }
    }

    .el-checkbox__label {
      display: block;
      width: 100%;
      height: 100%;
      padding: 0;
    }

    &.is-checked {
      .el-checkbox__input .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;

        &::after {
          border-color: #fff;
          border-width: 2px;
        }
      }
    }
  }
}

// 描述列表样式优化
:deep(.el-descriptions) {
  .el-descriptions__body {
    .el-descriptions__table {
      .el-descriptions__cell {
        padding: 12px;
      }
    }
  }
}
</style>
